package com.bdqn.controller;

import com.bdqn.pojo.Right;
import com.bdqn.pojo.Role;
import com.bdqn.pojo.User;
import com.bdqn.service.RightService;
import com.bdqn.service.RoleService;
import com.bdqn.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;


@Controller
public class IndexController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;
    @Resource
    private RightService rightService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private final String SHIRO_LOGIN_COUNT = "shiro_login_count_";

    /**
     * 去登录页
     */
    @GetMapping("/login")
    public String toLogin() {
        return "login";
    }

    /**
     * 执行登录操作
     */
    @PostMapping("/login")
    public String doLogin(HttpSession session, String usrName, String usrPassword, Model model) {
//        User loginUser = userService.login(usrName, usrPassword);
//        session.setAttribute("loginUser", loginUser);
//        return "redirect:/main";
        try {
//            usrPassword = userService.encryptPassword(usrPassword);
            UsernamePasswordToken token=new UsernamePasswordToken(usrName,usrPassword);
            Subject subject= SecurityUtils.getSubject();
            subject.login(token);
//            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT+usrName);
            // 认证(登录)成功
            User user=(User) subject.getPrincipal();
            session.setAttribute("loginUser",user);
            return "redirect:/main";
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            model.addAttribute("message","用户名或密码失败，登录失败！");
            return "login";
        }catch (LockedAccountException e){
            model.addAttribute("message","用户被禁用，登录失败！");
            return "login";
        }catch (AuthenticationException e){
            model.addAttribute("message","认证异常，登录失败！");
            return "login";
        }
    }

    /**
     * 跳转到主页
     */
    @GetMapping("/main")
    public String toMain() {
        return "main";
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }
    @GetMapping("/403")
    public String to403(){
        return "403";
    }


}

